package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.domain.SysDocument;
import com.sale.system.domain.dto.SysDocumentDto;
import com.sale.system.mapper.SysDocumentMapper;
import com.sale.system.service.ISysDocumentService;
import com.sale.system.service.ISysMidSplitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 单据配置
 * @Param 实现类
 * @return
 * @Date 22-11-22
 * @Author hl
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class SysDocumentServiceImpl implements ISysDocumentService {

    private final SysDocumentMapper sysDocumentMapper;

    private final ISysMidSplitService sysMidSplitService;


    /**
     * 查询单据配置
     *
     * @param sysDocument 单据配置
     * @return 单据配置
     */
    @Override
    public TableDataInfo<SysDocumentDto> selectDocumentList(SysDocument sysDocument, PageQuery pageQuery) {
        Page<SysDocumentDto> page = sysDocumentMapper.selectPageDocumentList(pageQuery.build(), this.buildQueryWrapper(sysDocument));
        List<SysDocumentDto> records = page.getRecords();
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "sys_handover_method");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for(SysDocumentDto entity : records){
            //交接方式
            entity.setDocHandoverMethodDict(statusMap.get(entity.getDocHandoverMethod()));
        }
        return TableDataInfo.build(page);
    }

    /**
     * 查询条件
     *
     * @param document
     * @return Wrapper
     */
    private Wrapper<SysDocument> buildQueryWrapper(SysDocument document) {
        Map<String, Object> params = document.getParams();
        QueryWrapper<SysDocument> wrapper = Wrappers.query();
        wrapper.like(ObjectUtil.isNotNull(document.getDocCode()), "t1.doc_code", document.getDocCode()).like(StringUtils.isNotBlank(document.getDocName()), "t1.doc_name", document.getDocName()).between(document.getBeginTime() != null && document.getEndTime() != null, "t1.create_time", document.getBeginTime(),document.getEndTime()).orderByDesc("t1.create_time");
        return wrapper;
    }

    /**
     * 根据id查询详情
     *
     * @param docId
     * @return
     */
    @Override
    public SysDocument selectDocumentListById(long docId) {
        SysDocument sys = sysDocumentMapper.selectDocumentListById(docId);
        if (sys.getDocHandoverMethod().equals("0")) {
            sys.setDocHandoverMethod("");
        }
        return sys;
    }

    /**
     * 删除单据配置
     *
     * @param docId 单据配置
     * @return 单据配置
     */
    @Override
    public int deleteDocumentById(String docId) {
        String[] docIdS = docId.split(",");
        return sysDocumentMapper.deleteDocumentById(docIdS);
    }

    /**
     * 新增单据配置
     *
     * @param sysDocument 单据配置
     * @return 单据配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDocument(SysDocument sysDocument) {

        // 设置创建人
        String createBy = LoginHelper.getUsername();
        sysDocument.setCreateBy(createBy);
        sysDocument.setCreateTime(new Date());
        int cn = sysDocumentMapper.insertDocument(sysDocument);

        // 判断配置单据是否唯一
        int i = sysDocumentMapper.selectDocConfigByIds((long) sysDocument.getDocConfig());
        if (i > 1) {
            throw new GlobalException("配置单据已存在！");
        }
        return cn;
    }

    /**
     * 修改单据配置
     *
     * @param sysDocument 单据配置
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDocument(SysDocument sysDocument){

        // 设置修改人
        String createBy = LoginHelper.getUsername();
        sysDocument.setCreateBy(createBy);
        sysDocument.setCreateTime(new Date());
        sysDocument.setUpdateTime(new Date());
        // 修改单据配置信息
        int cn = sysDocumentMapper.updateDocument(sysDocument);

        // 判断配置单据是否唯一
        int i = sysDocumentMapper.selectDocConfigByIds((long) sysDocument.getDocConfig());
        if (i > 1) {
            throw new GlobalException("配置单据已存在！");
        }
        return cn;
    }


    /**
     * 根据权限码返回生成编码
     * 远程调用接口
     */
    @Override
    public String selectAuthorityCoding(String docConfig) {
        String midCode = sysDocumentMapper.selectAuthorityCoding(docConfig);
        return sysMidSplitService.selectSplitStr(midCode);
    }

    /**
     * 根据配置单据查询单据配置详情信息
     * @param docConfig
     * @return feign远程调用接口
     */
    @Override
    public SysDocument selectDocumentConfigById(Long docConfig) {
        SysDocument sysDocument = sysDocumentMapper.getDataByCode(docConfig);
        if(sysDocument==null){
            throw new GlobalException("当前菜单未配置单据配置,请添加单据配置");
        }
        // 获取审核配置明细list
//        sysDocument.setDocumentAuditDtoList(sysDocumentMapper.selectDocumentAuditDtoList(sysDocument.getDocId()));
//        // 获取检验配置明细list
//        sysDocument.setDocumentCheckDtoList(sysDocumentMapper.selectDocumentCheckDtoList(sysDocument.getDocId()));

        return sysDocument;
    }


}
